﻿ //Inicio Funciones propias de GoogleMap (Esta sección debe ser remplazada cuando se trabaje BingMap)

function MapControl() {

    var map;
    var directionsDisplay;
    var infoWindowStop;
    var infoWindowPeopleCounter;
    var infoWindowGPSImei;
    var infoWindowClient;
    var geocoder;
    var polyRoute;
    var polygono;
    var car;
    var originImeiMarker;
    var pathPolygono;
    var polygonoMarkers;
    var directionsService;
    var routes;
    var clientsRoutes;
    var directionsDisplayClientsRoutes;
    var busRoutes;
    var directionsDisplayBusRoutes;
    var geocoderOrigin;
    var geocoderDestination;
    var GPSImeiBusRouteHistory;

    //var busRoutes;
    //var directionsDisplayBusRoutes;
    //var directionsServiceBusRoutes;

    var pathPolygono2;
    var polygono2;

    /*this.show = function (numPosList, latitudeList, longitudeList) {
        var position;
        var pathPolygono2 = new google.maps.MVCArray;

        var polygono2 = new google.maps.Polygon({
            strokeWeight: 3,
            fillColor: '#5555FF'
        });
        
        polygono2.setMap(this.map);


        for (h = 0; h < numPosList.length; h++) {
            position = new google.maps.LatLng(stringToFloatForPosition(latitudeList[h]), stringToFloatForPosition(longitudeList[h]));
            pathPolygono2.insertAt(pathPolygono2.length, position);
        }
        polygono2.setPaths(new google.maps.MVCArray([pathPolygono2]));
        return pathPolygono2;
    }

    this.clear = function (pathPolygono2)
    {
        try{pathPolygono2.clear();}
        catch (ex) { null;}
    }*/

    this.createPolygono = function (pathPolygono, numPosList, latitudeList, longitudeList) {

        this.clearPolygono(pathPolygono);

        var position;

        pathPolygono = new google.maps.MVCArray;
        
        var polygono = new google.maps.Polygon({
            strokeWeight: 3,
            fillColor: '#5555FF'
        });

        polygono.setMap(this.map);

        for (h = 0; h < numPosList.length; h++) {
            position = new google.maps.LatLng(stringToFloatForPosition(latitudeList[h]), stringToFloatForPosition(longitudeList[h]));
            pathPolygono.insertAt(pathPolygono.length, position);
        }
        polygono.setPaths(new google.maps.MVCArray([pathPolygono]));
        return pathPolygono;
    }

    this.clearPolygono = function (pathPolygono) {
        try { pathPolygono.clear(); }
        catch (ex) { null; }
    }

    this.initializeRoutesObjects = function(){
        this.directionsDisplay = new google.maps.DirectionsRenderer();
        this.directionsDisplay.setOptions({ preserveViewport: true });

        this.infoWindowStop = new google.maps.InfoWindow();
        this.infoWindowPeopleCounter = new google.maps.InfoWindow();
        
        this.geocoder = new google.maps.Geocoder();
        
        this.directionsService = new google.maps.DirectionsService();
        //this.routes = [];
        this.GPSImeiRoute = this.addMarker(null, null, null);
    }

    this.initializeRoutesManagerObject = function () {
        this.directionsDisplayClientsRoutes = new google.maps.DirectionsRenderer();
        this.directionsDisplayClientsRoutes.setOptions({ preserveViewport: true });
        this.initializeOriginImeiMarker();
        this.clientsRoutes = [];
        this.geocoderOrigin = new google.maps.Geocoder();
        this.geocoderDestination = new google.maps.Geocoder();
        this.directionsService = new google.maps.DirectionsService();

    }

    this.initializeBusRoutesManagerObject = function () {
        globalBusRoutesManager.directionsDisplay = new google.maps.DirectionsRenderer();
        globalBusRoutesManager.directionsDisplay.setOptions({ preserveViewport: true, suppressMarkers: true });
        globalBusRoutesManager.directionsService = new google.maps.DirectionsService();
    }

    this.initializeBusStopsManagerObject = function () {
        globalBusStopsManager.directionsDisplay = new google.maps.DirectionsRenderer();
        globalBusStopsManager.directionsDisplay.setOptions({ preserveViewport: true, suppressMarkers: true });
        globalBusStopsManager.directionsService = new google.maps.DirectionsService();
    }

    this.initializeBusStopsHistoryObject = function () {
        globalBusStopsRouteHistory.directionsDisplay = new google.maps.DirectionsRenderer();
        globalBusStopsRouteHistory.directionsDisplay.setOptions({ preserveViewport: true, suppressMarkers: true});
        globalBusStopsRouteHistory.directionsService = new google.maps.DirectionsService();
        globalBusStopsRouteHistory.GPSImeiRoute = this.addMarker(null, null, null);
        globalBusStopsRouteHistory.geocoder = new google.maps.Geocoder();
    }

    this.initializeClientsHistoryObject = function () {

        /*var polylineOptionsActual = new google.maps.Polyline({
            strokeColor: '#FF0000'
        });

        polylineOptionsActual = new google.maps.Polyline({
            strokeColor: '#9f98ff',
            strokeWeight: 5
        });

        var rendererOptions = {
            map: map,
            suppressMarkers: false//,
            //polylineOptions: polylineOptionsActual
        }*/

        //globalClientsRouteHistory.directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
        
        globalClientsRouteHistory.directionsDisplay = new google.maps.DirectionsRenderer({
            polylineOptions: {
                strokeColor: "red"
            }
        });
        globalClientsRouteHistory.directionsDisplay.setOptions({ preserveViewport: true, suppressMarkers: false});
        globalClientsRouteHistory.directionsService = new google.maps.DirectionsService();
        globalClientsRouteHistory.GPSImeiRoute = this.addMarker(null, null, null);
        globalClientsRouteHistory.geocoder = new google.maps.Geocoder();
    }

    this.initializeGeoFencesObjects = function () {
        this.pathPolygono = new google.maps.MVCArray;
        this.polygonoMarkers = [];
        this.initializePolygono();
    }



    this.initializeForScripts = function() {

        globalGenerateScripts.directionsDisplay = new google.maps.DirectionsRenderer();
        globalGenerateScripts.directionsDisplay.setOptions({ preserveViewport: true, suppressMarkers: true });
        globalGenerateScripts.directionsService = new google.maps.DirectionsService();

        globalGenerateScripts.directionsDisplay.setMap(this.map);

        //this.addListenerclientMapForScripts();

    }

    this.addListenerclientMapForScripts = function () {
        google.maps.event.addListener(this.map, 'click', function (event) {

            objMapControl.addMarkers(event.latLng);

            globalGenerateScripts.index = globalGenerateScripts.markerList.length - 1;
            if (globalGenerateScripts.index > 0) {
                objMapControl.calcRoute();
            }

        });
    }

    this.calcRoute = function () {
        var start = globalGenerateScripts.markerList[globalGenerateScripts.index - 1].marker.position;
        var end = globalGenerateScripts.markerList[globalGenerateScripts.index].marker.position;
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        globalGenerateScripts.directionsService.route(request, function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                if (globalGenerateScripts.routes == null) {
                    globalGenerateScripts.routes = result;
                }
                else {
                    globalGenerateScripts.routes.routes[0].legs.push(result.routes[0].legs[0]);
                }
                globalGenerateScripts.markerList[globalGenerateScripts.index].distance = result.routes[0].legs[0].distance.value;

                globalGenerateScripts.directionsDisplay.setDirections(globalGenerateScripts.routes);
            }
        });
    }

    this.addMarkers = function (latlng) {

        var marker = new google.maps.Marker({
            position: latlng,
            map: this.map,
            visible: true,
            draggable: true
        });

        google.maps.event.addListener(marker, 'dragend', function (event) {



            globalGenerateScripts.index = globalGenerateScripts.markerList.length - 1;
            if (globalGenerateScripts.index > 0) {
                globalGenerateScripts.markerList[globalGenerateScripts.markerList.length - 1].marker.position = this.getPosition();
                globalGenerateScripts.routes.routes[0].legs.pop();
                objMapControl.calcRoute();
            }

        });

        function Markers() {
            var marker;
            var distance;
            var moreSecond;

            this.setMarker = function (marker) {
                this.marker = marker;
                this.distance = 0;
                this.moreSecond = 0;
            };
        }

        var myMarker = new Markers();
        myMarker.setMarker(marker);

        for (i = 0; i < globalGenerateScripts.markerList.length; i++) {
            globalGenerateScripts.markerList[i].marker.draggable = false;
        }


        globalGenerateScripts.markerList.push(myMarker);
        //clipboardCopy('Ejemplo');
    }


    this.setPolygono = function(polygono)
    {
        //polygono.setMap(null);
        //polygono.setMap(this.map);
    }

    this.initializeMap = function () {

        var myLatLng = new google.maps.LatLng(10.060727, -84.43785);

        var myOptions = {
            center: myLatLng,
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            },
            panControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
        };        

        this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        
        this.infoWindowGPSImei = new google.maps.InfoWindow();
        this.infoWindowClient = new google.maps.InfoWindow();
        this.infoWindowGPSImei.disableAutoPan = false;


    }

    this.initializeMapBackup = function() {

        this.directionsDisplay = new google.maps.DirectionsRenderer();
        this.directionsDisplay.setOptions({ preserveViewport: true });

        this.directionsDisplayClientsRoutes = new google.maps.DirectionsRenderer();
        this.directionsDisplayClientsRoutes.setOptions({ preserveViewport: true });
        
        this.geocoderOrigin = new google.maps.Geocoder();
        this.geocoderDestination = new google.maps.Geocoder();
        this.infoWindowStop = new google.maps.InfoWindow();
        this.pathPolygono = new google.maps.MVCArray;
        this.geocoder = new google.maps.Geocoder();
        this.polygonoMarkers = [];
        this.directionsService = new google.maps.DirectionsService();
        this.routes = [];
        this.clientsRoutes = [];

        var myLatLng = new google.maps.LatLng(10.060727, -84.43785);
        var myOptions = {
            center: myLatLng,
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        
        this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        this.GPSImeiRoute = this.addMarker(null, null, null);


        this.initializeOriginImeiMarker();
        

    }

    this.initializeOriginImeiMarker = function()
    {
        this.originImeiMarker = this.addMarker(null, null, null);
        this.originImeiMarker.setDraggable(true);
        // Add dragging event listeners.
        /*google.maps.event.addListener(this.originImeiMarker, 'dragstart', function () {
            updateDirectionMarker('Dragging...');
        });

        google.maps.event.addListener(this.originImeiMarker, 'drag', function () {
            //updateMarkerStatus('Dragging...');
        });*/

        google.maps.event.addListener(this.originImeiMarker, 'dragend', function () {
            //updateMarkerStatus('Drag ended');
            var index = -1;
            index = getIndexGpsImei(globalRoutesManager.gpsImeiList, globalRoutesManager.gpsImeiSelected);
            if (index != -1) {
                globalRoutesManager.gpsImeiList[index].position = objMapControl.originImeiMarker.position;
                globalRoutesManager.gpsImeiList[index].address = objMapControl.originImeiMarker.position.lat() + "," + objMapControl.originImeiMarker.position.lng();
            }
        });
    }

    this.removeInitializeLogo = function ()
    {
        this.map.controls[google.maps.ControlPosition.CENTER].removeAt(0);
        google.maps.event.clearListeners(this.map, 'click');      
    }

    this.showHistoryRoute = function()
    {
        this.directionsDisplay.setMap(this.map);
    }
    
    this.hideHistoryRoute = function()
    {
        this.directionsDisplay.setMap(null);
    }

    this.showClientsRoutes = function () {
        this.directionsDisplayClientsRoutes.setMap(this.map);
    }

    this.showClientsDirectionDisplay = function (globalObject) {
        globalObject.directionsDisplay.setMap(this.map);
    }

    this.hideClientsRoutes = function () {
        this.directionsDisplayClientsRoutes.setMap(null);
    }


    /*this.showBusRoutes = function () {
        this.directionsDisplayBusRoutes.setMap(this.map);
    }*/
    
    this.showDirectionsDisplay = function (directionsDisplay){
        directionsDisplay.setMap(this.map);
    }

    /*this.hideDirectionsDisplay = function (directionsDisplay) {
        directionsDisplay.setMap(null);
    }*/

    /*this.hideBusRoutes = function () {
        this.directionsDisplayBusRoutes.setMap(null);
    }*/

    this.setDirectionsDisplay = function (directionsDisplay, route) {
        directionsDisplay.setDirections(route);
        //globalBusRoutesManager.directionsDisplay.setDirections(route);
    }

    this.hideDirectionsDisplay = function (directionsDisplay){
        directionsDisplay.setMap(null);
    }

    this.drawRoute = function(route)
    {
        this.directionsDisplay.setDirections(route);
    }

    this.drawRouteClient = function (route) {
        this.directionsDisplayClientsRoutes.setDirections(route);
    }

    /*this.drawBusRoute = function (route) {
        this.directionsDisplayBusRoutes.setDirections(route);
    }*/

    /*this.drawBusRouteStop = function (route) {
        globalBusStopsManager.directionsDisplay.setDirections(route);
    }*/
    
    this.addInfoWindow = function()
    {
        return new google.maps.InfoWindow();
    }

    this.setinfoWindowStopContent = function (content) {
        this.infoWindowStop.setContent(content);
    }

    this.setinfoWindowPeopleCounterContent = function (content) {
        this.infoWindowPeopleCounter.setContent(content);
    }

    this.infoWindowStopOpen = function (marker) {
        this.infoWindowStop.open(this.map, marker);
    }

    this.infoWindowPeopleCounterOpen = function (marker) {
        this.infoWindowPeopleCounter.open(this.map, marker);
    }

    this.setinfoWindowGPSImeiContent = function (content) {
        if (content != this.infoWindowGPSImei.getContent()) {
            this.infoWindowGPSImei.setContent(content);
        }
    }

    this.infoWindowGPSImeiOpen = function (marker) {
        this.infoWindowGPSImei.open(this.map, marker);
    }

    this.setinfoWindowClientContent = function (content) {
        if (this.infoWindowClient) {
            if (content != this.infoWindowClient.getContent()) {
                this.infoWindowClient.setContent(content);
            }
        }
    }

    this.infoWindowClientOpen = function (marker, title) {
        this.infoWindowClient.open(this.map, marker);
    }

    this.addClientMarker = function() {
        return new google.maps.Marker ({ map: this.map, draggable: true });
    }

    this.centerMap = function(position) {
        this.map.setCenter(position);
    }

    this.zoomMap = function (zoom) {
        this.map.setZoom(zoom);
    }

    this.addStopMarker = function (image, position, title)
    {
        var stopMarker = new google.maps.Marker({ map: this.map, icon: image, position: position, title: title });

        google.maps.event.addListener(stopMarker, 'click', function (event) {
            for (i = 0; i < globalList.stopsMarkers.length; i++) {
                if (objMapControl.getPositionXtoString(objMapControl.getPositionMarker(globalList.stopsMarkers[i].stopMarker)) == objMapControl.getPositionXtoString(event.latLng) && objMapControl.getPositionYtoString(objMapControl.getPositionMarker(globalList.stopsMarkers[i].stopMarker)) == objMapControl.getPositionYtoString(event.latLng)) {
                    objMapControl.setinfoWindowStopContent('<b>Hora en la que se detiene: ' + globalList.stopsMarkers[i].initialTimeStop + '<br/>' + 'Hora en la que continúa: ' + globalList.stopsMarkers[i].finalTimeStop);
                    objMapControl.infoWindowStopOpen(globalList.stopsMarkers[i].stopMarker);
                }
            }
        });

        return stopMarker;
    }

    this.addPeopleCounterMarker = function (image, position, title) {
        var peopleCounterMarker = new google.maps.Marker({ map: this.map, icon: image, position: position, title: title });

        google.maps.event.addListener(peopleCounterMarker, 'click', function (event) {
            for (i = 0; i < globalList.peopleCounterMarkers.length; i++) {
                if (objMapControl.getPositionXtoString(objMapControl.getPositionMarker(globalList.peopleCounterMarkers[i].peopleCounterMarker)) == objMapControl.getPositionXtoString(event.latLng) && objMapControl.getPositionYtoString(objMapControl.getPositionMarker(globalList.peopleCounterMarkers[i].peopleCounterMarker)) == objMapControl.getPositionYtoString(event.latLng)) {
                    objMapControl.setinfoWindowPeopleCounterContent( '<b>Personas que Ingresan: ' + globalList.peopleCounterMarkers[i].peopleIn +
                                                            '<br/> Personas que Salen: ' + globalList.peopleCounterMarkers[i].peopleOut +
                                                            '<br/> Personas Ingresaron en Total: ' + globalList.peopleCounterMarkers[i].peopleTotalIn + 
                                                            '<br/> Personas Salieron en Total: ' + globalList.peopleCounterMarkers[i].peopleTotalOut +
                                                            '<br/> Personas que estan Dentro en Total: ' + globalList.peopleCounterMarkers[i].peopleTotalInside);
                    objMapControl.infoWindowPeopleCounterOpen(globalList.peopleCounterMarkers[i].peopleCounterMarker);
                }
            }
        });

        return peopleCounterMarker;
    }

    this.getDirectionFromPosition = function (latlng) {
        this.geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    globalRoutes.direction = results[0].formatted_address;//getlbDirection().innerText = results[0].formatted_address;
                }
            } else {
                //alert("Geocoder failed due to: " + status);
            }
        });
    }

    this.getDirectionFromPositionBusHistory = function (latlng, globalObject) {
        globalObject.geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    globalObject.direction = results[0].formatted_address;//getlbDirection().innerText = results[0].formatted_address;
                }
            } else {
                //alert("Geocoder failed due to: " + status);
            }
        });
    }

    this.initializePolygono = function () {
        this.polygono = new google.maps.Polygon({
            strokeWeight: 3,
            fillColor: '#5555FF'
        });

        this.polyRoute = new google.maps.Polyline({
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 5
        });

        this.polyRoute.setMap(this.map);
        this.polygono.setMap(this.map);
        this.polygono.setPaths(new google.maps.MVCArray([this.pathPolygono]));
    }

    this.clearGeoFenceMarkers = function (clearAll) {

        this.pathPolygono.clear();

        var totalMarkers = this.polygonoMarkers.length;

        for (k = 0; k < totalMarkers; k++) {
            this.polygonoMarkers[k].setMap(null);
        }

        for (k = 0; k < totalMarkers; k++) {
            this.polygonoMarkers.pop();
        }

        if (clearAll)
        {
            for (k = 0; k < globalList.geoFence.length; k++) {
                globalList.geoFence[k].checked = false;
                getGeoFenceGrid().clearSelectedItems();
            }
        }

    }

    this.setPositionMarker = function (marker, position) {
        marker.setPosition(position);
    }

    this.getPositionMarker = function (marker) {
        return marker.position;
    }

    this.setVisibleMarker = function (marker, status){
        marker.setVisible(status);
    }

    this.setIconMarker = function (marker, image) {
        marker.setIcon(image);
    }

    this.setTitleMarker = function (marker, title) {
        marker.setTitle(title);
    }

    this.getTitleMarker = function(marker){
        return marker.getTitle();
    }

    this.addListenerClic = function () {
        google.maps.event.addListener(this.map, 'click', this.addGeoFenceMarkersClic);
    }

    this.clearListenerClic = function () {
        google.maps.event.clearListeners(this.map, 'click');
        //getCkbClient().enabled = false;
        //getCkbEnableDisableGeoFence().enabled = false;
    }

    this.addGeoFenceMarkersClic = function (event) {
        objMapControl.pathPolygono.insertAt(objMapControl.pathPolygono.length, event.latLng);

        var lmarker = new google.maps.Marker({
            position: event.latLng,
            map: objMapControl.map,
            draggable: true
        });
        objMapControl.polygonoMarkers.push(lmarker);


        lmarker.setTitle("#" + objMapControl.pathPolygono.length);

        google.maps.event.addListener(lmarker, 'click', function () {
            lmarker.setMap(null);
            for (var i = 0, I = objMapControl.polygonoMarkers.length; i < I && objMapControl.polygonoMarkers[i] != lmarker; ++i);
            objMapControl.polygonoMarkers.splice(i, 1);
            objMapControl.pathPolygono.removeAt(i);
        });

        google.maps.event.addListener(lmarker, 'dragend', function () {
            for (var i = 0, I = objMapControl.polygonoMarkers.length; i < I && objMapControl.polygonoMarkers[i] != lmarker; ++i);
            objMapControl.pathPolygono.setAt(i, lmarker.getPosition());
        });
    }

    this.addListenerClickBusRoute = function () {
        google.maps.event.addListener(this.map, 'click', this.addBusRouteMarkersClick);
    }

    this.clearMarkerFromMap = function (marker) {
        marker.setMap(null);
    }

    this.addBusRouteMarkersClick = function (event) {
        globalBusRoutesManager.isSeletedItemBusRoute = false;
        objMapControl.addBusRouteMarkersClickDB(event.latLng);
    }

    this.addBusRouteMarkersClickDB = function (latLng) {

        if (globalBusRoutesManager.isValidClickPoint){
            var lmarker = new google.maps.Marker({
                position: latLng,
                map: objMapControl.map,
                icon: images.locationBusRoute,
                draggable: true
            });
            if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 0) {
                globalBusRoutesManager.polygonoBusRouteMarkers[globalBusRoutesManager.polygonoBusRouteMarkers.length - 1].draggable = false;
            }
            globalBusRoutesManager.polygonoBusRouteMarkers.push(lmarker);
            globalBusRoutesManager.isClick = true;


            lmarker.setTitle("#" + globalBusRoutesManager.polygonoBusRouteMarkers.length);

            if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 1) {
                globalBusRoutesManager.originPoint = globalBusRoutesManager.polygonoBusRouteMarkers[globalBusRoutesManager.polygonoBusRouteMarkers.length - 2].position;
                globalBusRoutesManager.destinationPoint = globalBusRoutesManager.polygonoBusRouteMarkers[globalBusRoutesManager.polygonoBusRouteMarkers.length - 1].position;
                objMapControl.calculateBusRouteFromPointToPoint();
            }

            google.maps.event.addListener(lmarker, 'click', function () {



                for (var i = 0, I = globalBusRoutesManager.polygonoBusRouteMarkers.length; i < I && globalBusRoutesManager.polygonoBusRouteMarkers[i] != lmarker; ++i);

                if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 == i) {
                    lmarker.setMap(null);

                    if (globalBusRoutesManager.busRoutes.length) {
                        if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 == globalBusRoutesManager.busRoutes[0].legs.length) {
                            globalBusRoutesManager.busRoutes[0].legs.pop();
                            globalBusRoutesManager.response.routes = globalBusRoutesManager.busRoutes;
                        }
                    }

                    globalBusRoutesManager.polygonoBusRouteMarkers.splice(i, 1);

                    if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 0) {
                        globalBusRoutesManager.polygonoBusRouteMarkers[globalBusRoutesManager.polygonoBusRouteMarkers.length - 1].draggable = true;
                    }


                    if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 1) {
                        objMapControl.showDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                        objMapControl.setDirectionsDisplay(globalBusRoutesManager.directionsDisplay, globalBusRoutesManager.response);
                    }
                    else {
                        if (globalBusRoutesManager.busRoutes.length > 0) {
                            while (globalBusRoutesManager.busRoutes[0].legs.length > 0) {
                                globalBusRoutesManager.busRoutes[0].legs.pop();
                            }
                        }
                        objMapControl.hideDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                    }
                  
                    globalBusRoutesManager.isValidClickPoint = true;
                }
                else {
                    objWindowsMessageManager.show_Warning("Únicamente puede eliminar el último punto registrado llamado " + globalBusRoutesManager.polygonoBusRouteMarkers.length, titles.busRoutesTitle);
                }
            });

            google.maps.event.addListener(lmarker, 'dragend', function () {
                for (var i = 0, I = globalBusRoutesManager.polygonoBusRouteMarkers.length; i < I && globalBusRoutesManager.polygonoBusRouteMarkers[i] != lmarker; ++i);
                globalBusRoutesManager.isClick = false;
                if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 1) {
                    if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 == i) {

                        globalBusRoutesManager.originPoint = globalBusRoutesManager.polygonoBusRouteMarkers[i - 1].position;
                        globalBusRoutesManager.destinationPoint = globalBusRoutesManager.polygonoBusRouteMarkers[i].position;

                        if (globalBusRoutesManager.busRoutes.length > 0) {
                            if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 == globalBusRoutesManager.busRoutes[0].legs.length) {
                                globalBusRoutesManager.busRoutes[0].legs.pop();
                                globalBusRoutesManager.response.routes = globalBusRoutesManager.busRoutes;
                                if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 2) {
                                    objMapControl.setDirectionsDisplay(globalBusRoutesManager.directionsDisplay, globalBusRoutesManager.response);
                                }
                                else {
                                    if (globalBusRoutesManager.busRoutes.legs) {
                                        while (globalBusRoutesManager.busRoutes[0].legs.length > 0) {
                                            globalBusRoutesManager.busRoutes[0].legs.pop();
                                        }
                                    }
                                    objMapControl.hideDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                                }
                            }
                        }

                        objMapControl.calculateBusRouteFromPointToPoint();
                        globalBusRoutesManager.polygonoBusRouteMarkers[i] = lmarker;
                    }
                    else {
                        objWindowsMessageManager.show_Warning("Únicamente puede mover el último punto registrado llamado #" + globalBusRoutesManager.polygonoBusRouteMarkers.length, titles.busRoutesTitle);
                        globalBusRoutesManager.polygonoBusRouteMarkers[i].setPosition(globalBusRoutesManager.polygonoBusRouteMarkers[i].position);
                    }
                }
            });

            google.maps.event.addListener(lmarker, 'dragstart', function () {
                for (var i = 0, I = globalBusRoutesManager.polygonoBusRouteMarkers.length; i < I && globalBusRoutesManager.polygonoBusRouteMarkers[i] != lmarker; ++i);
                if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 != i) {
                    objWindowsMessageManager.show_Warning("Únicamente puede mover el último punto registrado llamado #" + globalBusRoutesManager.polygonoBusRouteMarkers.length, titles.busRoutesTitle);
                }
            });
        }
        else {
            objWindowsMessageManager.show_Warning("No se puede crear otro punto porque el punto anterior fue inválido.", titles.busRoutesTitle);
        }
    }

    this.addClientsRouteHistoryClickDB = function (latLng) {

        var lmarker = new google.maps.Marker({
            position: latLng,
            map: objMapControl.map,
            icon: images.locationBusRoute,
            draggable: false,
            visible: false
        });

        globalClientsRouteHistory.polygonoRouteMarkers.push(lmarker);

        lmarker.setTitle("#" + globalClientsRouteHistory.polygonoRouteMarkers.length);

        if (globalClientsRouteHistory.polygonoRouteMarkers.length > 1) {
            globalClientsRouteHistory.originPoint = globalClientsRouteHistory.polygonoRouteMarkers[globalClientsRouteHistory.polygonoRouteMarkers.length - 2].position;
            globalClientsRouteHistory.destinationPoint = globalClientsRouteHistory.polygonoRouteMarkers[globalClientsRouteHistory.polygonoRouteMarkers.length - 1].position;
            objMapControl.calculateClientRouteHistoryFromPointToPoint();
        }
    }

    this.addBusRouteHistoryClickDB = function (latLng) {

        var lmarker = new google.maps.Marker({
            position: latLng,
            map: objMapControl.map,
            icon: images.locationBusRoute,
            draggable: false,
            visible: false
        });

        globalBusStopsRouteHistory.polygonoBusRouteMarkers.push(lmarker);

        lmarker.setTitle("#" + globalBusStopsRouteHistory.polygonoBusRouteMarkers.length);

        if (globalBusStopsRouteHistory.polygonoBusRouteMarkers.length > 1) {
            globalBusStopsRouteHistory.originPoint = globalBusStopsRouteHistory.polygonoBusRouteMarkers[globalBusStopsRouteHistory.polygonoBusRouteMarkers.length - 2].position;
            globalBusStopsRouteHistory.destinationPoint = globalBusStopsRouteHistory.polygonoBusRouteMarkers[globalBusStopsRouteHistory.polygonoBusRouteMarkers.length - 1].position;
            objMapControl.calculateBusStopRouteHistoryFromPointToPoint();
        }
    }

    this.addBusRouteClickDB = function (latLng) {

            var lmarker = new google.maps.Marker({
                position: latLng,
                map: objMapControl.map,
                icon: images.locationBusRoute,
                draggable: false,
                visible: false
            });

            globalBusStopsManager.polygonoBusRouteMarkers.push(lmarker);

            lmarker.setTitle("#" + globalBusStopsManager.polygonoBusRouteMarkers.length);

            if (globalBusStopsManager.polygonoBusRouteMarkers.length > 1) {
                globalBusStopsManager.originPoint = globalBusStopsManager.polygonoBusRouteMarkers[globalBusStopsManager.polygonoBusRouteMarkers.length - 2].position;
                globalBusStopsManager.destinationPoint = globalBusStopsManager.polygonoBusRouteMarkers[globalBusStopsManager.polygonoBusRouteMarkers.length - 1].position;
                objMapControl.calculateBusStopRouteFromPointToPoint();
            }
    }

    this.addGeoFenceMarkersClicBD = function (latLng) {
        objMapControl.pathPolygono.insertAt(objMapControl.pathPolygono.length, latLng);

        var lmarker = new google.maps.Marker({
            position: latLng,
            map: this.map,
            draggable: true
        });
        objMapControl.polygonoMarkers.push(lmarker);


        lmarker.setTitle("#" + objMapControl.pathPolygono.length);

        google.maps.event.addListener(lmarker, 'click', function () {
            lmarker.setMap(null);
            for (var i = 0, I = objMapControl.polygonoMarkers.length; i < I && objMapControl.polygonoMarkers[i] != lmarker; ++i);
            objMapControl.polygonoMarkers.splice(i, 1);
            objMapControl.pathPolygono.removeAt(i);
        });

        google.maps.event.addListener(lmarker, 'dragend', function () {
            for (var i = 0, I = objMapControl.polygonoMarkers.length; i < I && objMapControl.polygonoMarkers[i] != lmarker; ++i);
            objMapControl.pathPolygono.setAt(i, lmarker.getPosition());
        });
    }

    this.addMarker = function (image, position, title, animation) {
        if (image == null) {
            if(animation == null)
                return new google.maps.Marker({ map: this.map, position: position, title: title });
            else
                return new google.maps.Marker({ map: this.map, position: position, title: title, animation: google.maps.Animation.DROP});
            
        }
        else {
            if(animation == null)
                return new google.maps.Marker({ map: this.map, icon: image, position: position, title: title });
            else
                return new google.maps.Marker({ map: this.map, icon: image, position: position, title: title, animation: google.maps.Animation.DROP });
        }
    }
    
    this.addListenerMarkerClickForOpenWindowsInfo = function (marker, content) {
        google.maps.event.addListener(marker, 'click', function () {
            objMapControl.setinfoWindowGPSImeiContent(content);
            objMapControl.infoWindowGPSImeiOpen(marker);
        });
    }

    this.getIconArrow = function (degree) {
        var icon = {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
            scale: 8,
            fillColor: "blue",
            fillOpacity: 0.8,
            strokeWeight: 1,
            rotation: degree //this is how to rotate the pointer
        };
        return icon;
    }

    this.addPosition = function (lat, lng) {
        return new google.maps.LatLng(lat, lng);
    }

    this.addImage = function (image) {
        return new google.maps.MarkerImage(images.location + image);
    }

    this.setCenterMap = function (position) {
        this.map.setCenter(position);
    }

    this.addListenerClientClick = function () {
        google.maps.event.addListener(this.map, 'click', this.addClientMarkersClic);
    }

    this.addClientMarkersClic = function (event) {
        globalClientManager.clientMarker.setPosition(event.latLng);
        
        globalClientManager.clientMarker.setDraggable(true);
    }

    this.addListenerBusStopsMarkersClick = function () {
        google.maps.event.addListener(this.map, 'click', this.addBusStopsMarkersClic);
    }

    this.addBusStopsMarkersClic = function (event) {
        globalBusStopsManager.busStopMarker.setPosition(event.latLng);

        globalBusStopsManager.busStopMarker.setDraggable(true);
    }

    this.nextPositionIndexRoute = function () {
        for (globalRoutes.currentIndexRoute = globalRoutes.currentIndexRoute + 1; globalRoutes.currentIndexRoute < globalRoutesManager.allClientsList.length; globalRoutes.currentIndexRoute++) {
            if (globalRoutesManager.allClientsList[globalRoutes.currentIndexRoute].checked && globalRoutesManager.allClientsList[globalRoutes.currentIndexRoute].numPos == null) {
                return true;
            }
        }
        return false;
    }

    this.calculateSmartRoute = function (address) {

        globalRoutes.currentIndexRoute = -1;
        globalRoutes.currentIndexNearClient = -1;

        if (objMapControl.nextPositionIndexRoute()) {
            objMapControl.calculateSmartRouteStart(address);
        }
        else {
            globalRoutes.responseEndObject.hide(globalRoutes.updatePanelObject);//responseEnd(getrpvRoutesManagerPanelUpdateControl());
            globalRoutes.btnGenerateRoute.value = "Generar Rutas";
        }
    }
   
    this.calculateSmartRouteStart = function (address) {

        if (address == null) {
            address = this.originImeiMarker.position.lat() + "," + this.originImeiMarker.position.lng();
        }

        var geocoderRequest = {
            address: address
        }

        this.geocoderOrigin.geocode(geocoderRequest, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                globalRoutes.originClient = results[0].geometry.location;
                setTimeout(objMapControl.calculateSmartRouteProcess, globalRoutes.timeToCalculateRouteClients);
            }
            else {
                if (objMapControl.nextPositionIndexRoute()) {
                    objMapControl.calculateSmartRouteProcess(globalRoutesManager.allClientsList[globalRoutes.currentIndexRoute].address);
                }
                else {//Se ignora y se vuelve a calcular
                    if (globalRoutes.currentIndexNearClient != -1) {
                        objMapControl.calculateSmartRoute(globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].address);
                    }
                    else {
                        objMapControl.calculateSmartRoute(null);
                    }
                }
            }
        });
    }

    this.addRowClientsGroupsRouteDataSource = function (index) {

        var tableView = globalRoutes.clientsRoutesSelectedTableView;

        globalRoutesManager.allClientsSelectedDataSource.push({ "NumPos": globalRoutesManager.allClientsList[index].numPos, "ClientID": globalRoutesManager.allClientsList[index].clientID, "ClientName": globalRoutesManager.allClientsList[index].clientName, "ClientGroupName": globalRoutesManager.allClientsList[index].clientGroupName, "KmsText": globalRoutesManager.allClientsList[index].kmsText, "DurationText": globalRoutesManager.allClientsList[index].durationText });

        tableView.set_dataSource(globalRoutesManager.allClientsSelectedDataSource);
        tableView.dataBind();
    }

    this.calculateSmartRouteProcess = function () {
        address = globalRoutesManager.allClientsList[globalRoutes.currentIndexRoute].address;
        var geocoderRequest = {
            address: address
        }

        objMapControl.geocoderDestination.geocode(geocoderRequest, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                globalRoutes.destinationClient = results[0].geometry.location;
                setTimeout(objMapControl.calculateSmartRouteValidation, globalRoutes.timeToCalculateRouteClients);
            }
            else {
                if (objMapControl.nextPositionIndexRoute()) {
                    setTimeout(objMapControl.calculateSmartRouteProcess, globalRoutes.timeToCalculateRouteClients);
                }
                else {//Se ignora y se vuelve a calcular
                    if (globalRoutes.totallyClients < globalRoutes.currentIndexNearClient) {
                        if (globalRoutes.currentIndexNearClient != -1) {
                            objMapControl.calculateSmartRoute(globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].address);
                        }
                        else {
                            objMapControl.calculateSmartRoute(null);
                        }
                    }
                    else {
                        objWindowsMessageManager.show_Warning("La posición no es válida.", "Histórico de Rutas");
                        globalRoutes.responseEndObject.hide(globalRoutes.updatePanelObject);
                    }

                }
            }
        });
    }

    this.calculateSmartRouteValidation = function () {
        var request = {
            origin: globalRoutes.originClient,
            destination: globalRoutes.destinationClient,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false,
            durationInTraffic: true
        };
        objMapControl.directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                if ((globalRoutes.currentIndexNearClient == -1) || (response.routes[0].legs[0].distance.value < globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].kms)) {
                    globalRoutes.currentIndexNearClient = globalRoutes.currentIndexRoute;
                    globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].kms = response.routes[0].legs[0].distance.value;
                    globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].kmsText = response.routes[0].legs[0].distance.text;
                    globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].duration = response.routes[0].legs[0].duration.value * 2;
                    
                    var hours = 0;
                    hours = Math.floor(globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].duration / 60 / 60);
                    
                    var minutes = 0;
                    minutes = Math.floor((globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].duration / 60)) - (hours * 60);

                    var durationText = '';
                    if(hours > 0){
                        durationText = hours.toString() + " h ";
                    }

                    durationText = durationText + minutes.toString() + " min";

                    globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].durationText = durationText;//response.routes[0].legs[0].duration.text;

                    globalRoutes.route = response.routes[0];
                }
                
                if (objMapControl.nextPositionIndexRoute()) {
                    setTimeout(objMapControl.calculateSmartRouteProcess, globalRoutes.timeToCalculateRouteClients);
                }
                else {//Es la mejor Ruta
                    globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].numPos = ++globalRoutes.numPos;
                    objMapControl.addRowClientsGroupsRouteDataSource(globalRoutes.currentIndexNearClient);
                    objMapControl.showClientsRoutes();
                    
                    globalRoutes.btnGenerateRoute.value = "Cliente " + (globalRoutesManager.allClientsSelectedDataSource.length + 1) + " de " + globalRoutes.totallyClients;

                    if (globalRoutes.firstClientRoute) {
                        objMapControl.clientsRoutes.push(globalRoutes.route);
                        globalRoutes.firstClientRoute = false;
                    }
                    else {
                        objMapControl.clientsRoutes[0].legs.push(globalRoutes.route.legs[0]);
                    }

                    response.routes = objMapControl.clientsRoutes;
                    objMapControl.drawRouteClient(response);

                    objMapControl.calculateSmartRoute(globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].address);
                }
            }
            else {
                if (objMapControl.nextPositionIndexRoute()) {
                    setTimeout(objMapControl.calculateSmartRouteProcess, globalRoutes.timeToCalculateRouteClients);
                }
                else {//Se ignora y se vuelve a calcular
                    if (globalRoutes.currentIndexNearClient != -1) {
                        objMapControl.calculateSmartRoute(globalRoutesManager.allClientsList[globalRoutes.currentIndexNearClient].address);
                    }
                    else {
                        objMapControl.calculateSmartRoute(null);
                    }
                }
            }
        });
    }

    this.calculateClientRouteHistoryFromPointToPoint = function () {
        var request = {
            origin: globalClientsRouteHistory.originPoint,
            destination: globalClientsRouteHistory.destinationPoint,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false
        };
        globalClientsRouteHistory.directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                globalClientsRouteHistory.route = response.routes[0];

                objMapControl.showDirectionsDisplay(globalClientsRouteHistory.directionsDisplay);

                if (globalClientsRouteHistory.firstRoute) {
                    globalClientsRouteHistory.routesList.push(globalClientsRouteHistory.route);
                    globalClientsRouteHistory.firstRoute = false;
                }
                else {
                    globalClientsRouteHistory.routesList[0].legs.push(globalClientsRouteHistory.route.legs[0]);
                }

                response.routes = globalClientsRouteHistory.routesList;
                globalClientsRouteHistory.response = response;

                objMapControl.setDirectionsDisplay(globalClientsRouteHistory.directionsDisplay, globalClientsRouteHistory.response);
            }
            else {
                null;
            }
        });
    }

    this.calculateBusStopRouteHistoryFromPointToPoint = function () {
        var request = {
            origin: globalBusStopsRouteHistory.originPoint,
            destination: globalBusStopsRouteHistory.destinationPoint,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false
        };
        globalBusStopsRouteHistory.directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                globalBusStopsRouteHistory.route = response.routes[0];

                objMapControl.showDirectionsDisplay(globalBusStopsRouteHistory.directionsDisplay);

                if (globalBusStopsRouteHistory.firstBusRoute) {
                    globalBusStopsRouteHistory.busRoutesList.push(globalBusStopsRouteHistory.route);
                    globalBusStopsRouteHistory.firstBusRoute = false;
                }
                else {
                    globalBusStopsRouteHistory.busRoutesList[0].legs.push(globalBusStopsRouteHistory.route.legs[0]);
                }

                response.routes = globalBusStopsRouteHistory.busRoutesList;
                globalBusStopsRouteHistory.response = response;

                objMapControl.setDirectionsDisplay(globalBusStopsRouteHistory.directionsDisplay, globalBusStopsRouteHistory.response);
            }
            else {
                null;
            }
        });
    }

    this.calculateBusStopRouteFromPointToPoint = function () {
        var request = {
            origin: globalBusStopsManager.originPoint,
            destination: globalBusStopsManager.destinationPoint,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false
        };
        globalBusStopsManager.directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                globalBusStopsManager.route = response.routes[0];

                objMapControl.showDirectionsDisplay(globalBusStopsManager.directionsDisplay);

                if (globalBusStopsManager.firstBusRoute) {
                    globalBusStopsManager.busRoutes.push(globalBusStopsManager.route);
                    globalBusStopsManager.firstBusRoute = false;
                }
                else {
                    globalBusStopsManager.busRoutes[0].legs.push(globalBusStopsManager.route.legs[0]);
                }

                response.routes = globalBusStopsManager.busRoutes;
                globalBusStopsManager.response = response;

                objMapControl.setDirectionsDisplay(globalBusStopsManager.directionsDisplay, globalBusStopsManager.response);
            }
            else {
                null;
            }
        });
    }

    this.calculateBusRouteFromPointToPoint = function () {
        var request = {
            origin: globalBusRoutesManager.originPoint,
            destination: globalBusRoutesManager.destinationPoint,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false
        };
       
            globalBusRoutesManager.directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {

                    globalBusRoutesManager.route = response.routes[0];

                    objMapControl.showDirectionsDisplay(globalBusRoutesManager.directionsDisplay);

                    if (globalBusRoutesManager.firstBusRoute) {
                        globalBusRoutesManager.busRoutes.push(globalBusRoutesManager.route);
                        globalBusRoutesManager.firstBusRoute = false;
                    }
                    else {
                        globalBusRoutesManager.busRoutes[0].legs.push(globalBusRoutesManager.route.legs[0]);
                    }

                    response.routes = globalBusRoutesManager.busRoutes;
                    globalBusRoutesManager.response = response;

                    globalBusRoutesManager.isValidClickPoint = true;
                    objMapControl.showDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                    
                    objMapControl.setDirectionsDisplay(globalBusRoutesManager.directionsDisplay, globalBusRoutesManager.response);

                }
                else {
                    if (globalBusRoutesManager.isSeletedItemBusRoute) {
                        globalBusRoutesManager.isValidClickPoint = false;
                        objWindowsMessageManager.show_Warning("No se pudo dibujar la ruta, vuelva a presionar la ruta para dibujarla nuevamente.", titles.busRoutesTitle);
                    }
                    else {
                        objWindowsMessageManager.show_Warning("El punto es inválido, debe seleccionar otro punto en el mapa.", titles.busRoutesTitle);
                        globalBusRoutesManager.isValidClickPoint = false;
                        objMapControl.showDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                        if (globalBusRoutesManager.busRoutes.length > 0) {
                            if (globalBusRoutesManager.polygonoBusRouteMarkers.length - 1 == globalBusRoutesManager.busRoutes[0].legs.length) {
                                globalBusRoutesManager.busRoutes[0].legs.pop();
                                globalBusRoutesManager.response.routes = globalBusRoutesManager.busRoutes;
                                if (globalBusRoutesManager.polygonoBusRouteMarkers.length > 2) {
                                    objMapControl.setDirectionsDisplay(globalBusRoutesManager.directionsDisplay, globalBusRoutesManager.response);
                                }
                                else {
                                    while (globalBusRoutesManager.busRoutes[0].legs.length > 0) {
                                        globalBusRoutesManager.busRoutes[0].legs.pop();
                                    }
                                    objMapControl.hideDirectionsDisplay(globalBusRoutesManager.directionsDisplay);
                                }
                            }
                        }
                    }
                }
            });
    }
    
    this.clearStopsMarkers = function() {
        var length = globalList.stopsMarkers.length;

        for (i = 0; i < length; i++) {
            globalList.stopsMarkers[i].stopMarker.setMap(null);
        }

        for (i = 0; i < length; i++) {
            globalList.stopsMarkers.pop();
        }
    }

    this.clearPeopleCounterMarkers = function () {
        var length = globalList.peopleCounterMarkers.length;

        for (i = 0; i < length; i++) {
            globalList.peopleCounterMarkers[i].peopleCounterMarker.setMap(null);
        }

        for (i = 0; i < length; i++) {
            globalList.peopleCounterMarkers.pop();
        }
    }

    this.getDrivingRoute = function () {
        var request = {
            origin: globalRoutes.origin,
            destination: globalRoutes.destination,
            //waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.DirectionsTravelMode['DRIVING'],
            unitSystem: google.maps.DirectionsUnitSystem['METRIC'],
            provideRouteAlternatives: false
        };
        objMapControl.directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {

                if (globalRoutes.firstRoute) {
                    objMapControl.routes.push(response.routes[0]);
                    globalRoutes.firstRoute = false;
                }
                else {
                    for (var i = 0; i < response.routes[0].legs[0].steps.length; i++) {
                        objMapControl.routes[0].legs[0].steps.push(response.routes[0].legs[0].steps[i]);
                    }
                    objMapControl.routes[0].legs[0].end_location = objMapControl.getPositionMarker(globalList.trackDataByImei[globalRoutes.currentGpsPoint + 1]);
                }

                response.routes = objMapControl.routes;
            
                objMapControl.drawRoute(response);
            
                if (!globalRoutes.lastOne) {
                    if (globalRoutes.isCenterRoute) {
                        objMapControl.map.setCenter(objMapControl.routes[0].legs[0].end_location);
                    }
                }
                globalRoutes.doesWorkDrawRouteCount = 0;
                globalRoutes.mtsRoute = globalRoutes.mtsRouteStar;
            }
            else {
                globalRoutes.doesnWorkDrawRoute = true;
                if (globalRoutes.doesWorkDrawRouteCount > 5) {
                    globalRoutes.mtsRoute = globalRoutes.mtsRouteFix;
                }
                globalRoutes.doesWorkDrawRouteCount++;
            }

        });
    }

    this.getDistanceKms = function (pinitialPosition, pfinalPosition) {

        var distance = google.maps.geometry.spherical.computeDistanceBetween(pinitialPosition, pfinalPosition);
        return distance / 1000.00;
    }

    this.addEventsDrag = function (pMyCar) {

        pMyCar.setDraggable(true);
        // Add dragging event listeners.
        google.maps.event.addListener(pMyCar, 'dragstart', function () {
            updateDirectionMarker('Dragging...');
        });

        google.maps.event.addListener(pMyCar, 'drag', function () {
            //updateMarkerStatus('Dragging...');
        });

        google.maps.event.addListener(pMyCar, 'dragend', function () {
            //updateMarkerStatus('Drag ended');
            objMapControl.getDirectionFromPosition(pMyCar.getPosition());
        });
    }

    this.getPositionYtoString = function (position) {
        return configDecimalSeparator(position.lng().toString());
    }

    this.getPositionXtoString = function (position) {
        return configDecimalSeparator(position.lat().toString());
    }
}
